/**
 * 
 */
var Imap = require('imap');
var inspect = require('util').inspect;

function EmailReceiver(config) {
	this.imap = new Imap({
		user : config.user,
		password : config.password,
		host : config.host,
		port : 993,
		tls : true
	});
}

module.exports.EmailReceiver = EmailReceiver;

EmailReceiver.prototype.imap = null;
EmailReceiver.prototype.constructor = EmailReceiver;
EmailReceiver.prototype.readAllEmails = function(folder, callback) {

	var self = this;
	self.imap.once('ready', function() {
		self.imap.openBox(folder, true, function(err, box) {
			console.log('-----------------' + folder);
			if (err) {
				throw err;
			}
			console.log('Start handle folder: [%s], message count: [%d]',
					folder, box.messages.total);
			var fetch = self.imap.seq.fetch('1:2', {
				bodies : [ 'HEADER.FIELDS (FROM TO SUBJECT DATE)', 'TEXT' ]
			});
			fetch.on('message', function(msg, seqno) {
				console.log('-----Handle message %d', seqno);
				readEmail(folder, msg, callback);
			});
			fetch.once('error', function(err) {
				console.log('Fetch error: ' + err);
			});
			fetch.once('end', function() {
				console.log('Done handle folder: %s', folder);
				self.imap.end();
			});
		});
	});

	self.imap.once('error', function(err) {
		callback(err);
	});

	self.imap.once('end', function() {
		console.log('Connection ended');
	});

	self.imap.connect();
};

function readEmail(folderName, msg, callback) {
	var result = {};
	msg.on('body', function(stream, info) {
		var buffer = '';
		stream.on('data', function(chunk) {
			buffer += chunk.toString('utf8');
		});
		stream.once('end', function() {
			result['folder'] = folderName;
			if (info.which === 'TEXT') {
				result['content'] = buffer;
			} else {
				var header = Imap.parseHeader(buffer);
				result['head'] = header;
			}
		});
	});
	msg.once('end', function() {
		callback(null, result);
	});
}
